package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/database"
	"server/internal/pkg/response"
)

// GroupApi GroupApi 角色管理
var GroupApi = new(groupApi)

type groupApi struct {
	model.UserGroup
}

// List 列表
func (groupApi) List(c *gin.Context) {
	Db := database.DB
	//groupId, _ := c.Get("group_id")
	//Db = Db.Where("pid=?", groupId)
	rules, _ := c.Get("rules")
	rulesString := rules.(string)
	if rulesString != "*" {
		Db = Db.Where("id <> 1")
	}
	_, list, _ := serv.UserGroup.Reads(Db) //树状图
	response.SuccessList(c, list, 0)
}

// Detail 单条
func (groupApi) Detail(c *gin.Context) {
	id := c.Query("id")

	_, detail := serv.UserGroup.Read(id)

	response.SuccessData(c, detail, "")
}

// Add 添加
func (a groupApi) Add(c *gin.Context) {
	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	if serv.UserGroup.Create(a.UserGroup).Error == nil {
		response.Success(c, "", "添加成功")
	} else {
		response.Fail(c, "", "添加失败")
	}
}

// Edit 编辑
func (a groupApi) Edit(c *gin.Context) {

	if err := c.ShouldBindJSON(&a); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	//7为普通用户 不可编辑
	if a.ID == 7 {
		response.Fail(c, "", "固定分组无法编辑")
		return
	}

	if serv.UserGroup.Update(a.UserGroup).Error == nil {
		response.Success(c, "", "编辑成功")
	} else {
		response.Fail(c, "", "编辑失败")
	}
}

// Del 删除
func (groupApi) Del(c *gin.Context) {
	type Param struct {
		Ids []int `json:"ids"`
	}
	var param Param
	if err := c.ShouldBindJSON(&param); err != nil {
		response.Fail(c, err.Error(), "参数错误")
		return
	}

	for _, v := range param.Ids {

		if v == 1 {
			response.Fail(c, "", "超级管理员无法删除")
			return
		}
		if v == 2 {
			response.Fail(c, "", "固定角色无法删除")
			return
		}
		if v == 3 {
			response.Fail(c, "", "固定角色无法删除")
			return
		}
	}

	if serv.UserGroup.Delete(param.Ids).Error == nil {
		response.Success(c, "", "删除成功")
	} else {
		response.Fail(c, "", "删除失败")
	}
}

// GetSelect 列表
func (groupApi) GetSelect(c *gin.Context) {
	Db := database.DB
	rules, _ := c.Get("rules")
	if rules.(string) != "*" {
		Db = Db.Where("id in ?", []int{2, 3})
	}

	_, list, _ := serv.UserGroup.Reads(Db) //树状图
	response.SuccessList(c, list, 0)
}
